"""注册接口"""

from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from werkzeug.security import generate_password_hash
from common.res import res, ValidationArgs, RESCODE
from models.user import UserModel


# 参数校验
parse = RequestParser(ValidationArgs)

parse.add_argument(
    "user_name", type=str, required=True, help="缺少用户名", trim=True
)

parse.add_argument("pwd", type=str, required=True, help="缺少密码", trim=True)

parse.add_argument(
    "check_pwd", type=str, required=True, help="请再次确认密码", trim=True
)


class Register(Resource):
    """注册"""

    def post(self):
        data = parse.parse_args()

        if len(data["pwd"]) < 6:
            return res(RESCODE.PARAMS_FAIL, message="密码不能小于6位")

        if data["pwd"] != data["check_pwd"]:
            return res(RESCODE.PARAMS_FAIL, message="两次输入密码不一致")

        if UserModel.find_by_username(data["user_name"]):
            return res(RESCODE.USER_REPEAT)

        try:
            model_data = {
                "user_name": data["user_name"],
                "pwd_hash": generate_password_hash(data["pwd"]),
            }

            print(f"{model_data}")
            user = UserModel(**model_data)
            user.create_user()

            return res(message="注册成功")

        except Exception as err:
            print(f"except {err}")

            return res(RESCODE.REG_FAIL)
